package com.example.barcodescanner;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import com.adtouch.shoppingcart.Product;
import com.adtouch.shoppingcart.ShoppingCartActivity;
import com.adtouch.shoppingcart.ShoppingCartHelper;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class DetailsActivity extends Activity {

	private static final String MEDIA = "media";

	private static final int LOCAL_AUDIO = 1;
	private static final int STREAM_AUDIO = 2;
	private static final int RESOURCES_AUDIO = 3;

	private static final int STREAM_VIDEO = 5;
	private static final int RESOURCES_VIDEO = 6;
	String URL = "http://adtouch.cloudfoundry.com/";
	String imageString = null;
	String videoLink = null;
	String barcodeId = null;
	String imageLink = null;

	String title = null;
	String desc = null;
	String model = null;
	String linkedUrl = null;

	String audioLink = null;
	String result = null;
	String msgText = null;
	JSONObject json;
	JSONObject product;
	JSONObject j;
	double lat;
	double lon;
	Uri uri;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_details);

	     //final List<Product> scart = ShoppingCartHelper.getCart();
	    // final Product curprod;//= new Product(null, null, null);
	    
	    final Product curprod=new Product("aaa","aa","35",1,null);
		
		ImageButton audio = (ImageButton) findViewById(R.id.ibAudio);
		ImageButton video = (ImageButton) findViewById(R.id.ibVideo);
		ImageButton map = (ImageButton) findViewById(R.id.ibMap);
		ImageButton cart = (ImageButton) findViewById(R.id.ibCart);
		ImageButton phone = (ImageButton) findViewById(R.id.ibPhone);
		ImageButton sms = (ImageButton) findViewById(R.id.ibSMS);
		
		Button viewcart = (Button) findViewById(R.id.bViewCart);

		/*
		 * JSON GET call
		 * 
		 * check what all present..
		 * 
		 * enable button.
		 */

		try {
			imageString = getIntent().getExtras().getString("data");
			json = new JSONObject(imageString);
			product = new JSONObject(json.getString("product"));

			barcodeId = json.getString("id");
			imageLink = json.getString("imageLink");
			title = product.getString("title");
			desc = product.getString("desc");
			model = product.getString("model");
			linkedUrl = json.getString("linkedUrl");
			videoLink = json.getString("videoLink");
			audioLink = json.getString("audioLink");
			
			///curprod=new Product(title, desc, model);
			curprod.setDescription(desc);
			curprod.setTitle(title);
			curprod.setProductcode(model);
			
		}

		catch (Exception ex) {
			System.out.println("Error in json");
			System.out.println("Exception :" + ex);
			ex.printStackTrace();
		}
		HttpClient httpclient = new DefaultHttpClient();

		String temp = URL + "rest/ad/barcode/" + barcodeId + "/image";
		System.out.println(temp);
		HttpGet request = new HttpGet(temp);
		// System.out.println("url is" + URL + barcodeId + "/image");

		HttpResponse response = null;
		InputStream in = null;
		Bitmap bmp = null;
		try {
			// response = httpclient.execute(request);

			ResponseHandler<String> handler = new BasicResponseHandler();

			// String result = httpclient.execute(request, handler);

			// System.out.println(result);

			in = httpclient.execute(request).getEntity().getContent();

			bmp = BitmapFactory.decodeStream(in);

			in.close();

			temp = URL + "rest/ad/barcode/" + barcodeId + "/locations";

			request = new HttpGet(temp);
			response = httpclient.execute(request);

			//curprod.setProductImage(BitmapFactory.decodeResource(this.getResources(),R.drawable.watchmen));
			curprod.setProductImage(bmp);
			result = httpclient.execute(request, handler);

			// System.out.println(response.getStatusLine().getStatusCode());

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		msgText = "Hey I would recommend you to buy the product at this link " + linkedUrl;
		ImageView image = (ImageView) findViewById(R.id.ivImage);
		image.setImageBitmap(bmp);
		uri = Uri.parse(linkedUrl);
		image.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intentaudio = new Intent(Intent.ACTION_VIEW,uri);
				startActivity(intentaudio);
			}
		});
		
		TextView tv = (TextView) findViewById(R.id.txtDesc);
		tv.setText("Desc : " + desc);
		tv = (TextView) findViewById(R.id.txtTitle);
		tv.setText("Title : " + title);
		tv = (TextView) findViewById(R.id.txtModel);
		tv.setText("Model : " + model);
		System.out.println(linkedUrl);
		tv = (TextView) findViewById(R.id.txtURL);
		tv.setText(linkedUrl);

		StatusLine statusLine = response.getStatusLine();
		// int result=statusLine.getStatusCode();

		request.addHeader("Content-type", "text/byte");
		request.addHeader("Accept", "application/json");

		// Bitmap bmp =
		// BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
		// ImageView image = (ImageView) findViewById(R.id.ivCode);
		// image.setImageBitmap(bimage);

		httpclient.getConnectionManager().shutdown();
		// Log.i(tag, result);

		audio.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intentaudio = new Intent(getApplicationContext(),
						AudioActivity.class);
				intentaudio.putExtra(MEDIA, STREAM_AUDIO);
				intentaudio.putExtra("link", audioLink);
				// browserIntent.putExtra("productCode", productCode);
				startActivity(intentaudio);
			}
		});

		video.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intentvideo = new Intent(getApplicationContext(),
						ProductActivity.class);
				intentvideo.putExtra(MEDIA, STREAM_VIDEO);
				intentvideo.putExtra("productCode", "bag1");
				intentvideo.putExtra("link", barcodeId);
				intentvideo.putExtra("videoLink", videoLink);
				startActivity(intentvideo);
			}
		});

		sms.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intentsms = new Intent(getApplicationContext(),
						SmsActivity.class);
					intentsms.putExtra("msgText", msgText);
				startActivity(intentsms);
			}
		});

		final int status = response.getStatusLine().getStatusCode();

		try {

			System.out.println("REsponse is : " + result);
			result = result.substring(1);
			result = result.substring(0, result.length() - 1);
			System.out.println("new result is: " + result);
			j = new JSONObject(result);
			System.out.println("J is : " + j);
			lat = j.getDouble("latitude");
			lon = j.getDouble("longitude");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		map.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub

				if (status == 200) {
					Intent intentmap = new Intent(getApplicationContext(),
							GpsActivity.class);
					intentmap.putExtra("lat", lat);
					intentmap.putExtra("lon", lon);
					startActivity(intentmap);
				} else {
					Toast pieceToast = Toast.makeText(getApplicationContext(),
							"No location details found", Toast.LENGTH_SHORT);
					pieceToast.show();
				}

			}
		});

		phone.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intentmap = new Intent(getApplicationContext(),
						CallActivity.class);
				startActivity(intentmap);
			
			}
		});

		
		cart.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				boolean incart;
				
				if(ShoppingCartHelper.getCart()==null)
				{
					ShoppingCartHelper.addtocart(curprod);
				}
				else
				{
					incart=ShoppingCartHelper.search(curprod);
					if(incart==false)
						ShoppingCartHelper.addtocart(curprod); 
				
					else
					{
						ShoppingCartHelper.addQuantity(curprod);
					}
				}
				//scart.add(curprod);
				    //finish();
			
			}
		});
		viewcart.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
			Intent viewShoppingCartIntent = new Intent(getBaseContext(), ShoppingCartActivity.class);
			startActivity(viewShoppingCartIntent);
			}
		});
		
	}
}